import React, { createContext, useEffect, useMemo, useState } from 'react'
import { createBrowserHistory as createHistory } from 'history'

export const RouterContext = createContext()
let roothistory = null

const Router = (props) => {
  // 缓存history
  const history = useMemo(() => {
    roothistory = createHistory()
    return roothistory
  }, [])

  const [location, setLocation] = useState(history.location)

  // console.log('location ===> ', location)

  useEffect(() => {
    // 监听location变化通知更新
    const unlist = history.listen((location) => {
      console.log('location ===> ', location)
      setLocation(location)
    })

    return () => {
      unlist && unlist()
    }
  }, [])

  return (
    <RouterContext.Provider
      value={{
        location,
        history,
        match: {
          pathname: '/',
          url: '/',
          params: {},
          isExact: location.pathname === '/',
        },
      }}
    >
      {/* <Son /> */}
      {props.children}
    </RouterContext.Provider>
  )
}

export default Router
